package com.lt.accesscontrolmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.accesscontrolmanager.domain.AccessControlDevice;
import com.lt.accesscontrolmanager.mapper.AccessControlDeviceMapper;
import com.lt.accesscontrolmanager.service.AccessControlDeviceSerivce;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;


@Service
public class AccessControlDeviceSerivceImpl extends ServiceImpl<AccessControlDeviceMapper,AccessControlDevice> implements AccessControlDeviceSerivce {

    @Autowired
    private AccessControlDeviceMapper deviceMapper;


    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    private static final String DEVICE_CACHE_KEY = "device_list";


    public Page<AccessControlDevice> getDevicesByBuildingName(String buildingId, int pageNum, int pageSize) {

        // 使用 MyBatis-Plus 进行分页查询
        Page<AccessControlDevice> devicePage = new Page<>(pageNum, pageSize);
//        QueryWrapper<AccessControlDevice> queryWrapper = new QueryWrapper<>();
//
//        if(buildingId!= null&& !"".equals(buildingId)){
//            queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("building_id", buildingId);
//        }
//        deviceMapper.selectPage(devicePage, queryWrapper);


//        List<AccessControlDevice> accessControlDevices = deviceMapper.selectList(devicePage, buildingId);
//        System.out.println(accessControlDevices);


        Page<AccessControlDevice> page = new Page<>(pageNum, pageSize);

//
        return deviceMapper.selectData(page,buildingId);

        //return devicePage; // 直接返回 MyBatis-Plus 的 Page 对象

    }
    // 添加设备
    public void addDevice(AccessControlDevice device) {
        deviceMapper.addDevice(device);
        // 清除缓存
        redisTemplate.delete(DEVICE_CACHE_KEY + "::" + device.getBuildingId());
    }

    // 启用/禁用设备
    public void updateDeviceStatus(Long id, int status) {
        deviceMapper.updateDeviceStatus(id, status);
        // 更新缓存
        redisTemplate.delete(DEVICE_CACHE_KEY + "::" + id);
    }


    @Override
    public void updateImg(String id,String imgUrl) {
        UpdateWrapper<AccessControlDevice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id); // 设置更新条件
        AccessControlDevice device = new AccessControlDevice();
        device.setImg(imgUrl); // 设置要更新的字段
        // 调用 MyBatis-Plus 的更新方法
        this.update(device, updateWrapper);
    }
}
